<template>
  <div class="patient">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="searchData" size="medium" label-width="100px">
        <el-col :span="8">
          <el-form-item label="患者" prop="patientId">
            <!--<el-input v-model="searchData.patientId" placeholder="请输入患者" clearable :style="{width: '100%'}">
            </el-input>-->
            <el-autocomplete
              v-model="searchData.pname"
              :fetch-suggestions="getNameData"
              placeholder="请输入姓名"
              @select="getChoose"
              clearable
            ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分组" prop="groupId">
            <el-select v-model="searchData.groupId" placeholder="请选择下拉选择">
              <el-option v-for="(item, index) in groups" :key="index" :label="item.name" :value="item.id"
                         :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="search">查询</el-button>
            <!--<el-button @click="resetForm">重置</el-button>-->
            <el-button type="primary" @click="add">快速建档</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-table
      :data="dataList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      v-show="dataList.length > 0"
    >
      <el-table-column label="名称" prop="name" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生日" prop="birth" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.birth }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" prop="tel" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="住址" prop="addr" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.addr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分组" prop="lastUpdateBy" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.lastUpdateBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用" prop="del" align="center">
        <template slot-scope="{ row }">
          <span>{{ !row.del }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="id" align="center" width="200">
        <template slot-scope="{ row }">
          <el-button type="primary" @click="edit(row)">编辑</el-button>
          <el-button type="primary" @click="group(row)">分组</el-button>
          <!--<el-button type="info" v-if="row.available" @click="lock(row)">锁定</el-button>
          <el-button type="primary" v-else @click="lock(row)">启用</el-button>-->
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="searchData.totalCount > 0"
                :total="searchData.totalCount"
                :page.sync="searchData.page"
                :limit.sync="searchData.pageSize"
                @pagination="search"
    />

    <el-dialog :visible.sync="dialogVisible" @close="onClose" title="快速建档">
      <el-form ref="addForm" :model="addData" :rules="addRules" size="medium" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addData.name " :disabled="target.id != null" placeholder="请输入姓名" clearable
                    :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addData.gender " placeholder="请选择性别" :disabled="target.id != null" clearable
                     :style="{width: '100%'}">
            <el-option v-for="(item, index) in genderOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="tel">
          <el-input v-model="addData.tel" placeholder="请输入手机号码" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="证件号码" prop="idCard ">
          <el-input v-model="addData.idCard " placeholder="请输入证件号码"
                    :disabled="target.id != null && target.idCard != null && target.idCard != ''"
                    clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="addData.addr" placeholder="请输入地址" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birth ">
          <el-date-picker v-model="addData.birth " format="yyyy-MM-dd " value-format="yyyy-MM-dd "
                          :style="{width: '100%'}" placeholder="请选择生日"
                          :disabled="target.id != null && target.birth != null && target.birth != ''"
                          clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark ">
          <el-input v-model="addData.remark " placeholder="请输入备注信息" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogGroupVisible" title="分组管理">
      <el-row>
        <el-col :span="4">
          <p class="grid-content bg-purple">姓名:{{target.name}}</p>
        </el-col>
        <el-col :span="4">
          <p class="grid-content bg-purple">性别:{{target.gender | gender}}</p>
        </el-col>
        <el-col :span="4">
          <p class="grid-content bg-purple">年龄:{{target.birth | age}}</p>
        </el-col>
        <el-col :span="6">
          <p class="grid-content bg-purple">联系电话:{{target.tel}}</p>
        </el-col>
        <el-col :span="6">
          <p class="grid-content bg-purple">住址:{{target.addr}}</p>
        </el-col>
        <el-col :span="24">
          <el-form ref="elGroupForm" :model="target" size="medium" label-width="100px">
            <el-form-item label="分组">
              <el-select v-model="groupId" placeholder="请选择下拉选择">
                <el-option v-for="(item, index) in groups" :key="index" :label="item.name" :value="item.id"
                           :disabled="item.disabled"></el-option>
              </el-select>
            <!--</el-form-item>
            <el-form-item>-->
              <el-button
                :disabled="this.groupId === null"
                type="primary"
                @click="grantGroup"
                style="margin-top: 2px;float: right;margin-right: 20px"
              >添加分组
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-table
        :data="myGroups"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        v-show="myGroups.length > 0"
      >
        <el-table-column label="名称" prop="name" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="id" align="center" width="200">
          <template slot-scope="{ row }">
            <el-button type="primary" @click="lock(row)">移除分组</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="searchGroup.totalCount > 0"
                  :total="searchGroup.totalCount"
                  :page.sync="searchGroup.page"
                  :limit.sync="searchGroup.pageSize"
                  @pagination="searchMyGroup"
      />
    </el-dialog>

  </div>
</template>
<script>
  import Pagination from "@/components/Pagination";
  import {getGroup, saveGroup, patients, groups, disGrantGroup, grantGroup} from "@/api/userGroup";
  import {getPatients, addPatients, editPatients} from "@/api/patient";

  export default {
    components: {Pagination},
    filters: {
      gender(g) {
        return g == 1 ? "男" : "女";
      },
      age(strBirthday) {
        if (strBirthday) {
          let strBirthdayArr = strBirthday.split("-");
          let d = new Date();
          let yearDiff = d.getFullYear() - strBirthdayArr[0];
          let monthDiff = d.getMonth() + 1 - strBirthdayArr[1];
          let dayDiff = d.getDate() - strBirthdayArr[2];
          let age =
            monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)
              ? yearDiff - 1
              : yearDiff;
          //判断有没有到生日,没到就减1
          return age <= 0 ? monthDiff + "月" : age + "岁";
        }
      }
    },
    data() {
      return {
        target: {},
        groupId: null,
        title: "新增客户分组",
        baseUrl: "",
        dataList: [],
        groups: [],
        searchData: {
          groupId: 0,
          available: 1,
          totalCount: 0,
          totalPage: 1,
          pageSize: 10
        },
        searchGroup: {
          id: null,
          totalCount: 0,
          totalPage: 1,
          pageSize: 10
        },
        myGroups: [],
        kindOptions: [{
          "label": "启用",
          "value": 1
        }, {
          "label": "锁定",
          "value": 0
        }],
        dialogGroupVisible: false,
        dialogVisible: false,
        addData: {
          name: "",
          gender: "",
          tel: "",
          idCard: "",
          addr: "",
          birth: '',
          remark: "",
        },
        addRules: {
          name: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          gender: [{
            required: true,
            message: '请选择性别',
            trigger: 'change'
          }],
          tel: [{
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          }, {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: '手机号码格式错误',
            trigger: 'blur'
          }],
          idCard: [],
          addr: [],
          birth: [],
          remark: [],
        },
        genderOptions: [{
          "label": "男",
          "value": 1
        }, {
          "label": "女",
          "value": 2
        }],
      };
    },
    mounted() {
    },
    watch: {},
    created() {
      window.app = this
      if (this.$route.params.groupId) {
        this.searchData.groupId = this.$route.params.groupId;
      }
      this.search();
      this.searchAllGroup();
    },
    methods: {
      grantGroup() {
        if (!this.groupId) {
          return;
        }
        grantGroup({idx: [this.target.id], id: this.groupId}).then(response => {
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: "用户划分分组成功",
              type: "success"
            });
            this.searchMyGroup();
          }
        })
      },
      lock(row) {
        disGrantGroup({idx: [this.target.id], id: row.id}).then(response => {
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
            this.searchMyGroup();
          }
        })
      },
      searchAllGroup() {
        getGroup({pageSize: 1000}).then(response => {
          if (response.code === 200) {
            this.groups = response.page.list;
            this.groups.push({id: 0, name: "全部"})
          }
        })
      },
      shallowCopy(src) {
        var dst = {};
        for (var prop in src) {
          if (src.hasOwnProperty(prop)) {
            dst[prop] = src[prop];
          }
        }
        return dst;
      },
      add() {
        this.dialogVisible = true
        this.target = {}
      },
      group(row) {
        this.dialogGroupVisible = true
        this.target = row
        this.searchGroup.id = this.target.id
        this.searchMyGroup()
      },
      searchMyGroup() {
        groups(this.searchGroup).then(response => {
          if (response.code === 200) {
            this.myGroups = response.page.list;
            this.myGroups.page = response.page.currPage;
            this.myGroups.totalPage = response.page.totalPage;
            this.myGroups.totalCount = response.page.totalCount;
          }
        })
      },
      edit(row) {
        this.dialogVisible = true
        this.addData = row
        this.target = this.shallowCopy(row)
      },
      search() {
        patients(this.searchData).then(response => {
          if (response.code === 200) {
            this.dataList = response.page.list
            this.searchData.page = response.page.currPage;
            this.searchData.totalPage = response.page.totalPage;
            this.searchData.totalCount = response.page.totalCount;
          }
        })
      },
      geTel(tel) {
        var reg = /^(\d{3})\d{4}(\d{4})$/;
        return tel.replace(reg, "$1****$2");
      },
      remote(data, cb) {
        let _that = this;
        getPatients(data).then(response => {
          if (response.code === 200) {
            let data = response.page.list;
            data.filter(function (a) {
              a.value = a.name + "-" + _that.geTel(a.tel);
            });
            cb(data);
          }
        });
      },
      //查询病人信息select
      getNameData(queryString, cb) {
        this.remote({name: queryString}, cb);
      },
      //获取病人名字查询
      getChoose(val) {
        this.searchData.patientId = val.id;
        this.searchData.name = val.name;
        this.searchData.page = 0;
        this.searchData.pageSize = 10;
        this.search()
      },
      onClose() {
        this.$refs['addForm'].resetFields()
      },
      close() {
        this.$emit('update:visible', false)
      },
      handelConfirm() {
        this.$refs['addForm'].validate(valid => {
          if (!valid) return
          if (this.addData.id) {
            editPatients({
              "pid": this.addData.id,
              "gender": this.addData.gender,
              "birth": this.addData.birth,
              "addr": this.addData.addr,
              "tel": this.addData.tel,
              "remark": this.addData.remark,
              "idCard": this.addData.idCard,
              "version": this.addData.version
            }).then(response => {
              if (response.code === 200) {
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: "success"
                });
                this.searchData.page = 0;
                this.searchData.pageSize = 10;
                this.dialogVisible = false
                this.search();
              }
            })
          } else {
            addPatients(this.addData).then(response => {
              if (response.code === 200) {
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: "success"
                });
                this.searchData.page = 0;
                this.searchData.pageSize = 10;
                this.dialogVisible = false
                this.search();
              }
            })
          }
          this.close();
        })
      },
    }
  };
</script>


<style lang="scss">

  .patient {
    margin-top: 20px;

    .el-autocomplete {
      width: 100%;
    }

    .el-table .warning-row {
      background: oldlace;
    }

    .el-table .success-row {
      background: #c2f9b3;
    }

  }


</style>
